//
//  HKLoginController.m
//  KSBridgeDesign
//
//  Created by huzhaoke on 2021/4/13.
//

#import "HKLoginController.h"
#import <Masonry/Masonry.h>
#import "HKUser.h"
#import "HKCommonDefine.h"
#import <Foundation/Foundation.h>
#import "HTTPURL.h"
#import "HKLoadingView.h"
#import "HKNotificationHandler.h"
#import "HKRegularHelper.h"
#import "HKToastHelper.h"
#import "UIView+properties.h"
#import "HKRequestDefine.h"
#import "UIView+HKSafeArea.h"
#import "UILabel+create.h"
#import "HKFontHelper.h"
#import <MJExtension/MJExtension.h>
#import "AppDelegate.h"
#import "HKToastView.h"
#import "HKAggrementView.h"
#import "HKShareWebViewControllerManager.h"

static NSString *kKSAggree = @"aggree";

static CGFloat kKSLeftMargin = 24.f;

static CGFloat kKSConstPhoneH = 20.f;
static CGFloat kKSConstPassWordH = 20.f;
static CGFloat kKSConstSendButtonH = 42.f;
static CGFloat kKSLineH = 1.f;
static CGFloat kKSTopViewH = 156;
static CGFloat kKSTopViewW = 120.f;

static CGFloat kKSMutableContentTopH = 94.f;
static CGFloat kKSMutableContentAndPhoneMargin = 118.f;
static CGFloat kKSMutablePhoneAndLineMargin = 20.f;
static CGFloat kKSMutableLineAndPasswordMargin = 39.f;
static CGFloat kKSMutablePasswordAndLineMargin = 20.f;
static CGFloat kKSMutableLineAndSendButtonMargin = 64.f;
static CGFloat kKSMutableSendButtonBottom = 140.f;


@interface HKLoginController () <UITextFieldDelegate>

@property (nonatomic, strong) UIImageView *topImageView;

@property (nonatomic, strong) UITextField *phonTextField;
@property (nonatomic, strong) UIView *phoneTextLineView;

@property (nonatomic, strong) UITextField *passwordTextField;
@property (nonatomic, strong) UIView *passwordLineView;

@property (nonatomic, strong) UIButton *loginButton;

@property (nonatomic, strong) UIView *bgView;

@property (nonatomic, strong) UITextField *kbTextField;
@property (nonatomic, strong) HKNotificationHandler *handler;

@property (nonatomic, assign) CGFloat viewHScale;

@property (nonatomic, strong) HKAggrementView *aggreeView;


@end

@implementation HKLoginController
-(void)viewWillAppear:(BOOL)animated{
    [self preferredStatusBarStyle];
    [HKUITool setStatusBarBackgroundColor:[UIColor whiteColor]];
}
+ (void)showLoginViewControllerWithCompletionBlock:(void (^)(BOOL isSuccess))completionBlock {
    if (WMglobalUser()) {
        if (completionBlock) {
            completionBlock(YES);
        }
    } else {
        HKLoginController *controller = [HKLoginController new];
        UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:controller];
        if (completionBlock) {
            controller.completionBlock = completionBlock;
        }
        navi.modalPresentationStyle = 0;
        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:navi animated:NO completion:nil];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.userDefinedNaviBar.hidden = YES;
    self.viewHScale = [self currentViewRate];
    [self setupSubViews];
    [self setupNotifications];
}

- (void)setupSubViews {
    [self.view addSubview:self.topImageView];
    [self.view addSubview:self.bgView];
    [self.view addSubview:self.phonTextField];
    [self.view addSubview:self.phoneTextLineView];
    [self.view addSubview:self.passwordTextField];
    [self.view addSubview:self.passwordLineView];
    [self.view addSubview:self.loginButton];
    [self.bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
    
    CGFloat top = [self contentTop];
    [self.topImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(top);
        make.centerX.mas_equalTo(self.view);
        make.height.mas_equalTo(kKSTopViewH);
        make.width.mas_equalTo(kKSTopViewW);
    }];
    
    [self.phonTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.topImageView.mas_bottom).offset(kKSMutableContentAndPhoneMargin * self.viewHScale);
        make.left.mas_equalTo(kKSLeftMargin);
        make.right.mas_equalTo(self.view).offset(-kKSLeftMargin);
        make.height.mas_equalTo(kKSConstPhoneH);
    }];
    [self.phoneTextLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(kKSLeftMargin);
        make.right.mas_equalTo(-kKSLeftMargin);
        make.height.mas_equalTo(1);
        make.top.mas_equalTo(self.phonTextField.mas_bottom).offset(kKSMutablePhoneAndLineMargin * self.viewHScale);
    }];
    
    [self.passwordTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(kKSLeftMargin);
        make.right.mas_equalTo(-kKSLeftMargin);
        make.height.mas_equalTo(kKSConstPassWordH);
        make.top.mas_equalTo(self.phoneTextLineView.mas_bottom).offset(kKSMutableLineAndPasswordMargin * self.viewHScale);
    }];
    [self.passwordLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(kKSLeftMargin);
        make.right.mas_equalTo(-kKSLeftMargin);
        make.height.mas_equalTo(1);
        make.top.mas_equalTo(self.passwordTextField.mas_bottom).offset(kKSMutablePasswordAndLineMargin * self.viewHScale);
    }];
    
    [self.loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(kKSLeftMargin);
        make.right.mas_equalTo(-kKSLeftMargin);
        make.height.mas_equalTo(kKSConstSendButtonH);
        make.top.mas_equalTo(self.passwordLineView.mas_bottom).offset(kKSMutableLineAndSendButtonMargin);
    }];
}

- (void)setupNotifications {
    self.handler = [HKNotificationHandler new];
    WS
    [self.handler setKeyboardSizeChangeBlock:^(BOOL show, CGSize size) {
        SS
        if (show) {
            CGFloat offsetH = size.height -self.kbTextField.theHeightFromScreenBottom;
            if (offsetH > 0) {
                self.view.frame = CGRectMake(0, -offsetH - 10, self.view.width, self.view.height);
            }
        } else {
            self.view.frame = CGRectMake(0, 0, self.view.width, self.view.height);
        }
    }];
    [self.handler setTextFieldTextDidChangeBlock:^{
        SS
        if (self.kbTextField == self.phonTextField) {
            if (self.kbTextField.text.length >= 11) {
                NSString *text = self.kbTextField.text;
                NSString *subString = [text substringToIndex:11];
                self.kbTextField.text = subString;
                BOOL isMatch = [HKRegularHelper checkTelNumber:subString];
                if (!isMatch) {
                    [HKToastHelper showInvalidPhoneToast];
                }
            }
        }
    }];
}

- (void)onTapTap:(id)sender {
    [self.phonTextField endEditing:YES];
    [self.passwordTextField endEditing:YES];
}

#pragma mark - textFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    self.kbTextField = textField;
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField == _passwordTextField) {
        [self onTapSend:nil];
    }
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    
}

#pragma mark - btn Action
- (void)onTapBack:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)onTapSend:(id)sender {
    if (self.phonTextField.text <= 0 || self.passwordTextField.text.length <= 0) {
        [[HKToastView sharedToastView] showToast:@"必须输入手机号或者密码"];
        return;
    }
    
    NSString *text = self.phonTextField.text;
    if (text.length < 11) {
        [HKToastHelper showInvalidPhoneToast];
        return;
    }
    NSString *subString = [text substringToIndex:11];
    BOOL isMatch = [HKRegularHelper checkTelNumber:subString];
    if (!isMatch) {
        
        return;
    }
    [self.phonTextField endEditing:YES];
    [self.passwordTextField endEditing:YES];
    [self.view addSubview:self.aggreeView];
    [self.aggreeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
}

- (void)login {
    NSDictionary *params = @{@"username" : self.phonTextField.text ?: @"",
                             @"password" : self.passwordTextField.text ?:@""};
    NSString *url = HKLoginUrl;
    [[HKLoadingView loadingView] showLoading];
    [HTTPURL postRequest:url parameters:params success:^(NSURLSessionDataTask *task, NSDictionary *  responseObject) {
        [[HKLoadingView loadingView] hideLoading];
        NSDictionary *response = KSSAFE_CAST(responseObject, NSDictionary);
        NSDictionary *data = response[@"data"];
        if (data) {
            HKUser *user = [HKUser mj_objectWithKeyValues:response[@"data"][@"user"]];
            
            user.token = KSSAFE_CAST(response[@"data"][@"token"], NSString);
            
            [JPUSHService setAlias:[NSString stringWithFormat:@"%@_alias", user.phone] completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
                if (iResCode == 0) {
                    NSLog(@"添加别名成功");
                }
            } seq:1];
                
            if (user) {
                updateUser(user);
                if (self.completionBlock) {
                    [self dismissViewControllerAnimated:NO completion:nil];
                    self.completionBlock(YES);
                }
            }
            [HKShareWebViewControllerManager sharedInstance];
            [[HKToastView sharedToastView] showToast:@"登录成功"];
            [[AppDelegate appDelegate] initAppRootVC];
        } else {
            [[HKToastView sharedToastView] showToast:@"登录返回数据错误"];
        }
    } filure:^(NSURLSessionDataTask *task, NSError *error) {
        [[HKLoadingView loadingView] hideLoading];
        [[HKToastView sharedToastView] showToast:error.domain?: @"网络请求失败"];
    }];
}

#pragma mark - <#Section#>
- (CGFloat)currentViewRate {
    CGFloat top = [[UIApplication sharedApplication].keyWindow ks_safeAreaInsets].top;
    CGFloat statusBarH = [self statusBarH];
    CGFloat bottom = [[UIApplication sharedApplication].keyWindow ks_safeAreaInsets].bottom;
    CGFloat constRealH =  top + bottom + statusBarH + kKSConstPhoneH * 2 + kKSLineH * 2 + kKSTopViewH + kKSConstSendButtonH;
    
    CGFloat realMultiH = self.view.height - constRealH;
    CGFloat multiH = kKSMutableContentTopH + kKSMutableContentAndPhoneMargin + kKSMutablePhoneAndLineMargin + kKSMutableLineAndPasswordMargin +kKSMutablePasswordAndLineMargin + kKSMutableLineAndSendButtonMargin + kKSMutableSendButtonBottom;
    return realMultiH / multiH;
}

- (CGFloat)statusBarH {
    return 24.f;
}

- (CGFloat)contentTop {
    CGFloat top = [[UIApplication sharedApplication].keyWindow ks_safeAreaInsets].top;
    CGFloat statusBarH = [self statusBarH];
    CGFloat contentTop = top + statusBarH + kKSMutableContentTopH * self.viewHScale;
    return contentTop;
}

- (void)onTapAggree:(id)sender {
    [self login];
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kKSAggree];
}

#pragma mark - ios13
- (UIModalPresentationStyle)modalPresentationStyle{
    return UIModalPresentationFullScreen;
}

#pragma mark - properties
- (UIImageView *)topImageView {
    if (!_topImageView) {
        _topImageView = [UIImageView new];
        _topImageView.image = [UIImage imageNamed:@"loginTopImage"];
    }
    return _topImageView;
}

- (UITextField *)phonTextField {
    if (!_phonTextField) {
        _phonTextField = [[UITextField alloc] initWithFrame:CGRectZero];
        _phonTextField.textColor = UIColorFromRGB(0x828282);
        _phonTextField.clearButtonMode = UITextFieldViewModeAlways;
        _phonTextField.returnKeyType = UIReturnKeySend;
        _phonTextField.keyboardType = UIKeyboardTypeNumberPad;
        _phonTextField.leftViewMode = UITextFieldViewModeAlways;
        _phonTextField.font = [HKFontHelper appcnFontWithSize:14.f];
        _phonTextField.delegate = self;
        
        UIView *leftView = [UIView new];
        UILabel *leftLabel = [UILabel labelWithFont:[HKFontHelper appcnFontWithSize:14.f] bgColor:nil textColor:UIColorFromRGB(0x828282) textAligment:NSTextAlignmentLeft];
        leftLabel.text = @"手机号*";
        [leftLabel sizeToFit];
        leftView.frame = CGRectMake(0, 0, leftLabel.width + 10, kKSConstPhoneH);
        [leftView addSubview:leftLabel];
        _phonTextField.leftView = leftView;
    }
    return _phonTextField;
}

- (UITextField *)passwordTextField {
    if (!_passwordTextField) {
        _passwordTextField = [[UITextField alloc] initWithFrame:CGRectZero];
        _passwordTextField.textColor = UIColorFromRGB(0x828282);
        _passwordTextField.clearButtonMode = UITextFieldViewModeAlways;
        _passwordTextField.returnKeyType = UIReturnKeySend;
        _passwordTextField.keyboardType = UIKeyboardTypeDefault;
        _passwordTextField.leftViewMode = UITextFieldViewModeAlways;
        _passwordTextField.font = [HKFontHelper appcnFontWithSize:14.f];
        _passwordTextField.delegate = self;
        _passwordTextField.secureTextEntry = YES;
        
        UIView *leftView = [UIView new];
        UILabel *leftLabel = [UILabel labelWithFont:[HKFontHelper appcnFontWithSize:14.f] bgColor:nil textColor:UIColorFromRGB(0x828282) textAligment:NSTextAlignmentLeft];
        leftLabel.text = @"登录密码*";
        [leftLabel sizeToFit];
        leftView.frame = CGRectMake(0, 0, leftLabel.width + 10, kKSConstPhoneH);
        [leftView addSubview:leftLabel];
        _passwordTextField.leftView = leftView;
    }
    return _passwordTextField;
}

- (UIButton *)loginButton {
    if (!_loginButton) {
        UIButton *sendButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 93.f, kKSConstSendButtonH)];
        sendButton.backgroundColor = UIColorFromRGBA(0x4448ff, 1);
        sendButton.layer.cornerRadius = kKSConstSendButtonH / 2;
        sendButton.layer.masksToBounds = YES;
        [sendButton setTitleColor:UIColorFromRGBA(0xffffff, 1) forState:UIControlStateNormal];
        [sendButton.titleLabel setFont:[UIFont boldSystemFontOfSize:16.f]];
        [sendButton setTitle:@"登录" forState:UIControlStateNormal];
        [sendButton addTarget:self action:@selector(onTapSend:) forControlEvents:UIControlEventTouchUpInside];
        sendButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
        _loginButton = sendButton;
    }
    return _loginButton;
}

- (UIView *)phoneTextLineView {
    if (!_phoneTextLineView) {
        _phoneTextLineView = [UIView new];
        _phoneTextLineView.backgroundColor = UIColorFromRGB(0xF2F2F2);
    }
    return _phoneTextLineView;
}

- (UIView *)bgView {
    if (!_bgView) {
        _bgView = [UIView new];
        _bgView.backgroundColor = [UIColor clearColor];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTapTap:)];
        UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(onTapTap:)];
        
        [_bgView addGestureRecognizer:tap];
        [_bgView addGestureRecognizer:swipe];
    }
    return _bgView;
}


- (UIView *)passwordLineView {
    if (!_passwordLineView) {
        _passwordLineView = [UIView new];
        _passwordLineView.backgroundColor = UIColorFromRGB(0xF2F2F2);
    }
    return _passwordLineView;
}

- (HKAggrementView *)aggreeView {
    if (!_aggreeView) {
        _aggreeView = [HKAggrementView new];
        [_aggreeView.aggreeButton addTarget:self action:@selector(onTapAggree:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _aggreeView;
}

@end
